import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { 
  getExams, 
  getExamDetail, 
  startExam,
  getExamQuestions,
  submitAnswer,
  submitExam,
  getExamResult,
  getMyExams,
  getExamRecords
} from '@/api/exam'

export const useExamStore = defineStore('exam', () => {
  // 状态
  const exams = ref([])
  const currentExam = ref(null)
  const examSession = ref(null)
  const questions = ref([])
  const currentQuestionIndex = ref(0)
  const answers = ref({})
  const examResult = ref(null)
  const myExams = ref([])
  const examRecords = ref([])
  const loading = ref(false)
  const examTimer = ref(null)
  const timeRemaining = ref(0)
  const examStatus = ref('not_started') // not_started, in_progress, paused, completed, expired
  const searchKeyword = ref('')
  const filters = ref({
    category: '',
    type: '',
    difficulty: '',
    status: '',
    sort: 'latest'
  })
  const pagination = ref({
    page: 1,
    limit: 12,
    total: 0,
    totalPages: 0
  })

  // 计算属性
  const currentQuestion = computed(() => {
    return questions.value[currentQuestionIndex.value] || null
  })

  const totalQuestions = computed(() => questions.value.length)

  const answeredQuestions = computed(() => {
    return Object.keys(answers.value).length
  })

  const unansweredQuestions = computed(() => {
    return totalQuestions.value - answeredQuestions.value
  })

  const examProgress = computed(() => {
    if (totalQuestions.value === 0) return 0
    return Math.round((answeredQuestions.value / totalQuestions.value) * 100)
  })

  const isExamInProgress = computed(() => examStatus.value === 'in_progress')
  const isExamCompleted = computed(() => examStatus.value === 'completed')
  const isExamExpired = computed(() => examStatus.value === 'expired')

  const formattedTimeRemaining = computed(() => {
    const hours = Math.floor(timeRemaining.value / 3600)
    const minutes = Math.floor((timeRemaining.value % 3600) / 60)
    const seconds = timeRemaining.value % 60
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  })

  // 获取考试列表
  const fetchExams = async (params = {}) => {
    try {
      loading.value = true
      const queryParams = {
        page: pagination.value.page,
        limit: pagination.value.limit,
        keyword: searchKeyword.value,
        ...filters.value,
        ...params
      }
      
      const response = await getExams(queryParams)
      const { data, total, page, limit } = response.data
      
      exams.value = data
      pagination.value = {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
      
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取考试详情
  const fetchExamDetail = async (examId) => {
    try {
      loading.value = true
      const response = await getExamDetail(examId)
      currentExam.value = response.data
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 开始考试
  const startExamSession = async (examId) => {
    try {
      loading.value = true
      const response = await startExam(examId)
      examSession.value = response.data
      examStatus.value = 'in_progress'
      
      // 获取考试题目
      await fetchExamQuestions(examId, examSession.value.id)
      
      // 设置考试时间
      if (currentExam.value?.duration) {
        timeRemaining.value = currentExam.value.duration * 60 // 转换为秒
        startTimer()
      }
      
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取考试题目
  const fetchExamQuestions = async (examId, sessionId) => {
    try {
      const response = await getExamQuestions(examId, sessionId)
      questions.value = response.data
      currentQuestionIndex.value = 0
      answers.value = {}
      return response
    } catch (error) {
      throw error
    }
  }

  // 提交答案
  const submitQuestionAnswer = async (questionId, answer) => {
    try {
      if (!examSession.value) return
      
      const response = await submitAnswer(
        currentExam.value.id,
        examSession.value.id,
        {
          questionId,
          answer,
          timeSpent: 0 // 可以记录答题时间
        }
      )
      
      // 更新本地答案
      answers.value[questionId] = answer
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 提交考试
  const submitExamSession = async () => {
    try {
      loading.value = true
      
      if (!examSession.value) {
        throw new Error('没有活跃的考试会话')
      }
      
      const response = await submitExam(
        currentExam.value.id,
        examSession.value.id
      )
      
      examStatus.value = 'completed'
      stopTimer()
      
      // 获取考试结果
      await fetchExamResult(currentExam.value.id, examSession.value.id)
      
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取考试结果
  const fetchExamResult = async (examId, sessionId) => {
    try {
      const response = await getExamResult(examId, sessionId)
      examResult.value = response.data
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取我的考试
  const fetchMyExams = async (params = {}) => {
    try {
      const response = await getMyExams(params)
      myExams.value = response.data.data || response.data
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取考试记录
  const fetchExamRecords = async (params = {}) => {
    try {
      const response = await getExamRecords(params)
      examRecords.value = response.data.data || response.data
      return response
    } catch (error) {
      throw error
    }
  }

  // 导航到指定题目
  const goToQuestion = (index) => {
    if (index >= 0 && index < questions.value.length) {
      currentQuestionIndex.value = index
    }
  }

  // 下一题
  const nextQuestion = () => {
    if (currentQuestionIndex.value < questions.value.length - 1) {
      currentQuestionIndex.value++
    }
  }

  // 上一题
  const prevQuestion = () => {
    if (currentQuestionIndex.value > 0) {
      currentQuestionIndex.value--
    }
  }

  // 设置答案
  const setAnswer = (questionId, answer) => {
    answers.value[questionId] = answer
  }

  // 获取答案
  const getAnswer = (questionId) => {
    return answers.value[questionId]
  }

  // 开始计时器
  const startTimer = () => {
    if (examTimer.value) {
      clearInterval(examTimer.value)
    }
    
    examTimer.value = setInterval(() => {
      if (timeRemaining.value > 0) {
        timeRemaining.value--
      } else {
        // 时间到，自动提交考试
        examStatus.value = 'expired'
        stopTimer()
        submitExamSession()
      }
    }, 1000)
  }

  // 停止计时器
  const stopTimer = () => {
    if (examTimer.value) {
      clearInterval(examTimer.value)
      examTimer.value = null
    }
  }

  // 暂停考试
  const pauseExam = () => {
    examStatus.value = 'paused'
    stopTimer()
  }

  // 恢复考试
  const resumeExam = () => {
    examStatus.value = 'in_progress'
    startTimer()
  }

  // 设置搜索关键词
  const setSearchKeyword = (keyword) => {
    searchKeyword.value = keyword
  }

  // 设置筛选条件
  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
  }

  // 重置筛选条件
  const resetFilters = () => {
    filters.value = {
      category: '',
      type: '',
      difficulty: '',
      status: '',
      sort: 'latest'
    }
    searchKeyword.value = ''
  }

  // 设置分页
  const setPagination = (page, limit) => {
    pagination.value.page = page
    if (limit) {
      pagination.value.limit = limit
    }
  }

  // 清除当前考试
  const clearCurrentExam = () => {
    currentExam.value = null
    examSession.value = null
    questions.value = []
    currentQuestionIndex.value = 0
    answers.value = {}
    examResult.value = null
    examStatus.value = 'not_started'
    timeRemaining.value = 0
    stopTimer()
  }

  // 重置考试状态
  const resetExamState = () => {
    clearCurrentExam()
    exams.value = []
    myExams.value = []
    examRecords.value = []
    loading.value = false
    searchKeyword.value = ''
    resetFilters()
    pagination.value = {
      page: 1,
      limit: 12,
      total: 0,
      totalPages: 0
    }
  }

  // 获取题目状态
  const getQuestionStatus = (questionId) => {
    if (answers.value[questionId] !== undefined) {
      return 'answered'
    }
    return 'unanswered'
  }

  // 获取已答题目列表
  const getAnsweredQuestionIds = () => {
    return Object.keys(answers.value)
  }

  // 获取未答题目列表
  const getUnansweredQuestionIds = () => {
    return questions.value
      .filter(q => answers.value[q.id] === undefined)
      .map(q => q.id)
  }

  return {
    // 状态
    exams,
    currentExam,
    examSession,
    questions,
    currentQuestionIndex,
    answers,
    examResult,
    myExams,
    examRecords,
    loading,
    examTimer,
    timeRemaining,
    examStatus,
    searchKeyword,
    filters,
    pagination,
    
    // 计算属性
    currentQuestion,
    totalQuestions,
    answeredQuestions,
    unansweredQuestions,
    examProgress,
    isExamInProgress,
    isExamCompleted,
    isExamExpired,
    formattedTimeRemaining,
    
    // 方法
    fetchExams,
    fetchExamDetail,
    startExamSession,
    fetchExamQuestions,
    submitQuestionAnswer,
    submitExamSession,
    fetchExamResult,
    fetchMyExams,
    fetchExamRecords,
    goToQuestion,
    nextQuestion,
    prevQuestion,
    setAnswer,
    getAnswer,
    startTimer,
    stopTimer,
    pauseExam,
    resumeExam,
    setSearchKeyword,
    setFilters,
    resetFilters,
    setPagination,
    clearCurrentExam,
    resetExamState,
    getQuestionStatus,
    getAnsweredQuestionIds,
    getUnansweredQuestionIds
  }
}, {
  persist: {
    key: 'exam-store',
    storage: localStorage,
    paths: ['myExams', 'examRecords']
  }
})